Component({
  properties: {
    // 从父组件接收的数据
    productInformation: {
      type: Object,
      value: {}
    },
    selectedServiceConfigs: {
      type: Object,
      value: {}
    },
    serviceConfigs: {
      type: Array,
      value: []
    },
    address: {
      type: Object,
      value: {}
    },
    selectedTimeInfo: {
      type: Object,
      value: {}
    },
    availableTimeList: {
      type: Array,
      value: []
    },
    pickupInputs: {
      type: Array,
      value: []
    }
  },

  data: {
    // 组件内部数据
    keyboardHeight: '180rpx',
    isPickupInputFocus: false
  },

  methods: {
    // 选择服务配置
    selectServiceConfig(e) {
      const { serviceIndex, optionIndex } = e.currentTarget.dataset;
      const { serviceConfigs, selectedServiceConfigs } = this.data;
      
      const serviceConfig = serviceConfigs[serviceIndex];
      const selectedOption = serviceConfig.options[optionIndex];
      const optionKey = `${serviceIndex}_${optionIndex}`;
      
      const newSelectedServiceConfigs = { ...selectedServiceConfigs };
      if (newSelectedServiceConfigs[optionKey]) {
        delete newSelectedServiceConfigs[optionKey];
      } else {
        newSelectedServiceConfigs[optionKey] = {
          serviceIndex,
          optionIndex,
          selectedService: selectedOption,
          quantity: 1
        };
      }
      
      // 计算总数量并更新包裹组件
      const totalQuantity = this.calculateTotalQuantity(newSelectedServiceConfigs);
      this.updatePickupInputs(totalQuantity);
      
      // 触发父组件事件
      this.triggerEvent('serviceConfigChange', {
        selectedServiceConfigs: newSelectedServiceConfigs
      });
    },

    // 调整服务数量
    adjustServiceQuantity(e) {
      const { serviceIndex, optionIndex, action } = e.currentTarget.dataset;
      const { selectedServiceConfigs } = this.data;
      const optionKey = `${serviceIndex}_${optionIndex}`;
      const newSelectedServiceConfigs = { ...selectedServiceConfigs };
      
      if (newSelectedServiceConfigs[optionKey]) {
        const currentQuantity = newSelectedServiceConfigs[optionKey].quantity || 1;
        if (action === 'increase') {
          newSelectedServiceConfigs[optionKey].quantity = currentQuantity + 1;
        } else if (action === 'decrease' && currentQuantity > 1) {
          newSelectedServiceConfigs[optionKey].quantity = currentQuantity - 1;
        } else if (action === 'decrease' && currentQuantity === 1) {
          delete newSelectedServiceConfigs[optionKey];
        }
        
        // 计算总数量并更新包裹组件
        const totalQuantity = this.calculateTotalQuantity(newSelectedServiceConfigs);
        this.updatePickupInputs(totalQuantity);
        
        this.triggerEvent('serviceConfigChange', {
          selectedServiceConfigs: newSelectedServiceConfigs
        });
      }
    },

  // 地址选择
  onAddressSelect() {
    console.log('pickup-service: onAddressSelect 被点击');
    this.triggerEvent('addressSelect');
  },

    // 时间选择
    onTimeSelect() {
      this.triggerEvent('timeSelect');
    },

    // 快递点选择
    pickupAddressSelection(e) {
      const index = e.currentTarget.dataset.index;
      const { pickupInputs, productInformation } = this.data;
      
      // 兼容 packageStations 可能为 undefined 的情况
      const packageStations = (productInformation && productInformation.product && productInformation.product.packageStations) || [];
      if (!Array.isArray(packageStations) || packageStations.length === 0) {
        wx.showToast({ title: '暂无可选快递点', icon: 'none' });
        return;
      }
      wx.showActionSheet({
        itemList: [...packageStations],
        success: (res) => {
          pickupInputs[index].stationName = packageStations[res.tapIndex];
          this.setData({ pickupInputs });
          
          // 触发父组件事件
          this.triggerEvent('pickupInputsChange', { pickupInputs });
          
          // 通知父组件重新计算价格
          this.triggerEvent('priceRecalculate');
        },
        fail: (err) => {},
      });
    },

    // 显示取件码弹窗
    showPopup(e) {
      const index = e.currentTarget.dataset.index;
      const { pickupInputs } = this.data;
      pickupInputs[index].isPopupVisible = true;
      this.setData({ pickupInputs });
    },

    // 输入取件码
    onInputChange(e) {
      const index = e.currentTarget.dataset.index;
      const { pickupInputs } = this.data;
      pickupInputs[index].tempCode = e.detail.value;
      this.setData({ pickupInputs });
    },

    // 确认取件码
    confirmPickupCode(e) {
      const index = e.currentTarget.dataset.index;
      const { pickupInputs } = this.data;
      pickupInputs[index].code = pickupInputs[index].tempCode;
      pickupInputs[index].isPopupVisible = false;
      this.setData({ pickupInputs });
      
      this.triggerEvent('pickupInputsChange', { pickupInputs });
    },

    // 关闭弹窗
    closePopup(e) {
      const index = e.currentTarget.dataset.index;
      const { pickupInputs } = this.data;
      pickupInputs[index].isPopupVisible = false;
      this.setData({ pickupInputs });
    },

    // 上传包裹图片
    async uploadPickupPhoto(e) {
      const { index } = e.currentTarget.dataset;
      const pickupInputs = [...this.data.pickupInputs];
      
      try {
        const { tempFilePaths } = await wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
        });

        wx.showLoading({
          title: '上传中...',
          mask: true,
        });

        const cloudPath = `pickup-photos/${Date.now()}-${index}.jpg`;
        const uploadResult = await wx.cloud.uploadFile({
          cloudPath,
          filePath: tempFilePaths[0],
        });

        const publicUrl = this.getPublicURL(uploadResult.fileID);
        
        if (!pickupInputs[index].photos) {
          pickupInputs[index].photos = [];
        }
        
        pickupInputs[index].photos.push(publicUrl);
        
        this.setData({ pickupInputs });
        this.triggerEvent('pickupInputsChange', { pickupInputs });
        wx.hideLoading();
        wx.showToast({
          title: '上传成功',
          icon: 'success',
        });
      } catch (error) {
        wx.hideLoading();
        console.error('上传包裹图片失败:', error);
        wx.showToast({
          title: '上传失败',
          icon: 'none',
        });
      }
    },

    // 预览包裹图片
    previewPickupPhoto(e) {
      const { packageIndex, photoIndex } = e.currentTarget.dataset;
      const pickupInputs = this.data.pickupInputs;
      const photos = pickupInputs[packageIndex].photos || [];
      
      if (photos.length > 0) {
        wx.previewImage({
          current: photos[photoIndex],
          urls: photos,
        });
      }
    },

    // 删除包裹图片
    deletePickupPhoto(e) {
      const { packageIndex, photoIndex } = e.currentTarget.dataset;
      const pickupInputs = [...this.data.pickupInputs];
      
      wx.showModal({
        title: '确认删除',
        content: '确定要删除这张图片吗？',
        success: (res) => {
          if (res.confirm) {
            pickupInputs[packageIndex].photos.splice(photoIndex, 1);
            this.setData({ pickupInputs });
            this.triggerEvent('pickupInputsChange', { pickupInputs });
            wx.showToast({
              title: '删除成功',
              icon: 'success',
            });
          }
        },
      });
    },

    // 获取公共URL
    getPublicURL(fileID) {
      if (!fileID.startsWith('cloud://')) return fileID;
      const envPart = fileID.split('/')[2];
      const envId = envPart.split('.')[1];
      const filePath = fileID.split('/').slice(3).join('/');
      const encodedPath = encodeURI(filePath);
      return `https://${envId}.tcb.qcloud.la/${encodedPath}`;
    },

    // 阻止事件冒泡
    preventBubble() {
      return;
    },

    // 处理键盘高度变化
    onKeyboardheightchange(e) {
      const { height } = e.detail;
      this.setData({
        keyboardHeight: height > 0 ? `${height}px` : '180rpx'
      });
    },

    // 计算总数量
    calculateTotalQuantity(selectedServiceConfigs) {
      let totalQuantity = 0;
      Object.values(selectedServiceConfigs).forEach(config => {
        if (config && config.quantity) {
          totalQuantity += config.quantity;
        }
      });
      return totalQuantity;
    },

    // 更新包裹组件
    updatePickupInputs(totalQuantity) {
      const currentPickupInputs = this.data.pickupInputs || [];
      const newPickupInputs = [];
      
      // 确保包裹数量与总数量一致
      for (let i = 0; i < totalQuantity; i++) {
        if (i < currentPickupInputs.length) {
          // 保留现有的包裹信息
          newPickupInputs.push(currentPickupInputs[i]);
        } else {
          // 添加新的包裹信息
          newPickupInputs.push({
            stationName: '',
            code: '',
            photos: [],
            isPopupVisible: false,
            tempCode: ''
          });
        }
      }
      
      this.setData({ pickupInputs: newPickupInputs });
      this.triggerEvent('pickupInputsChange', { pickupInputs: newPickupInputs });
    }
  }
}); 